#include "mainwidget.h"
#include "ui_mainwidget.h"
#include <QtCore/qmath.h>

MainWidget::MainWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MainWidget)
{
    ui->setupUi(this);
}

MainWidget::~MainWidget()
{
    delete ui;
}

bool MainWidget::IsDigitString(const QString &str)
{
   int length = str.length();
   for (int i = 0; i < length; ++i) {
       if (str[i] < '0' || str[i] > '9')
           return false;
   }

   return true;
}

void MainWidget::on_ComputeBtn_clicked()
{
    QString rate = ui->RateEdit->text();
    if (!IsDigitString(rate))
        return;

    QString day = ui->DayEdit->text();
    if (!IsDigitString(day))
        return;

    QString fishDay = ui->FishDayEdit->text();
    if (!IsDigitString(fishDay))
        return;

    QString restDay = ui->RestDayEdit->text();
    if (!IsDigitString(restDay))
        return;

    QString loseRatio = ui->LoseRatioEdit->text();
    if (!IsDigitString(loseRatio))
        return;

    float fRate = rate.isEmpty()? 0 : rate.toInt() / static_cast<float>(100);
    float fLoseRate = loseRatio.isEmpty()? 0 : loseRatio.toInt() / static_cast<float>(100);
    int iDay = day.isEmpty()? 0 : day.toInt();
    int iFishDay = fishDay.isEmpty()? 0 : fishDay.toInt();
    int iRestDay = restDay.isEmpty()? 0 : restDay.toInt();
    if (iFishDay == 0)
        return;
    if (iFishDay < iRestDay)
        return;

    if (iDay < iFishDay) {
        return;
    }

    float rate1 = static_cast<float>(iFishDay - iRestDay) / iFishDay;
    int day1 = static_cast<int>(iDay * rate1);
    int day2 = iDay - day1;
    double result = qPow(static_cast<qreal>(1 + fRate), day1) * qPow(static_cast<qreal>(1 - fLoseRate), day2);
    QString resultStr = QString::number(result);
    ui->ResultEdit->setText(resultStr);
}
